﻿namespace Shutterstock.Salesforce.Tools
{
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using Shutterstock.Salesforce.Tools.SFPartner;    
    
    internal sealed class SFConnection : IDisposable, ISalesForceConnection
    {
        private LoginResult m_LoginResult;
        private string m_SFSession;
        private SforceService m_SFService;

        private void AssertLoggedIn()
        {
            if (m_SFService == null)
            {
                throw new InvalidOperationException("Not logged in.  Must call Login() before this is available");
            }
        }

        public string SFInstance
        {
            get
            {
                AssertLoggedIn();
                return m_SFSession;
            }
        }

        public string SFSession
        {
            get
            {
                AssertLoggedIn();
                return m_LoginResult.sessionId;
            }
        }

        /// <summary>
        /// Login to Salesforce 
        /// </summary>
        /// <param name="username">username to login with</param>
        /// <param name="password">password</param>
        public void Login(string username, string password)
        {
            m_SFService = new SforceService();
            m_LoginResult = m_SFService.login(username, password);
            m_SFService.SessionHeaderValue = new SessionHeader();
            m_SFService.SessionHeaderValue.sessionId = m_LoginResult.sessionId;
            m_SFService.Url = m_LoginResult.serverUrl;
            Regex instanceRegex = new Regex("https://(.*)/services");
            Match m = instanceRegex.Match(m_SFService.Url);
            m_SFSession = m.Groups[1].Value;
        }

        public void Dispose()
        {
            
            m_SFService.logout();
            m_SFService.Dispose();
        }

        public SforceService SalesForceService
        {
            get { return m_SFService; }
        }

    }
}

